package com.sddnytsh.body_buildingsystem.screens

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Divider
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.sddnytsh.body_buildingsystem.components.CommentItem
import com.sddnytsh.body_buildingsystem.components.SimpleAvatarImage
import com.sddnytsh.body_buildingsystem.components.DefaultAvatar
import com.sddnytsh.body_buildingsystem.config.NetworkConfig
import com.sddnytsh.body_buildingsystem.data.state.UserState
import com.sddnytsh.body_buildingsystem.network.CommunityApiService
import com.sddnytsh.body_buildingsystem.topic.Comment
import com.sddnytsh.body_buildingsystem.utils.DateUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import android.util.Log
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.IOException

// 获取评论详情的函数
suspend fun getCommentById(commentId: Long, currentUserId: Long? = null): Comment? {
    data class CommentApiResponse<T>(
        val success: Boolean,
        val data: T
    )

    data class CommentData(
        val id: Long,
        val postId: Long,
        val userId: Long,
        val content: String,
        val likeCount: Int,
        val isLiked: Boolean?,
        val createdAt: String,
        val author: String,
        val authorAvatar: String?, // 🔥 添加作者头像字段
        val parentId: Long?,
        val rootId: Long?,
        val isDeleted: Boolean
    )

    return withContext(Dispatchers.IO) {
        val url = if (currentUserId != null) {
            "${NetworkConfig.BASE_URL}/api/post-comments/$commentId?currentUserId=$currentUserId"
        } else {
            "${NetworkConfig.BASE_URL}/api/post-comments/$commentId"
        }

        val client = OkHttpClient.Builder()
            .connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
            .readTimeout(8, java.util.concurrent.TimeUnit.SECONDS)
            .writeTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .connectionPool(okhttp3.ConnectionPool(5, 5, java.util.concurrent.TimeUnit.MINUTES))
            .build()
        val request = Request.Builder()
            .url(url)
            .build()

        client.newCall(request).execute().use { response ->
            if (!response.isSuccessful) {
                throw IOException("Unexpected code $response")
            }

            val responseBody = response.body?.string()
            val gson = Gson()
            val apiResp: CommentApiResponse<CommentData> = gson.fromJson(
                responseBody,
                object : TypeToken<CommentApiResponse<CommentData>>() {}.type
            )
            if (apiResp.success) {
                val commentData = apiResp.data
                Comment(
                    id = commentData.id,
                    postId = commentData.postId,
                    userId = commentData.userId,
                    content = commentData.content,
                    likeCount = commentData.likeCount,
                    isLiked = commentData.isLiked ?: false,
                    createdAt = commentData.createdAt,
                    author = commentData.author,
                    authorAvatar = commentData.authorAvatar, // 🔥 添加作者头像字段
                    parentId = commentData.parentId,
                    rootId = commentData.rootId,
                    isDeleted = commentData.isDeleted
                )
            } else {
                null
            }
        }
    }
}

// 获取评论回复列表的函数
suspend fun getRepliesByCommentId(commentId: Long, currentUserId: Long? = null): List<Comment> {
    data class CommentApiResponse<T>(
        val success: Boolean,
        val data: T
    )
    
    data class NestedData(
        val replies: List<Map<String, Any>>
    )

    return withContext(Dispatchers.IO) {
        val url = if (currentUserId != null) {
            "${NetworkConfig.BASE_URL}/api/post-comments/replies/$commentId?currentUserId=$currentUserId"
        } else {
            "${NetworkConfig.BASE_URL}/api/post-comments/replies/$commentId"
        }

        val client = OkHttpClient.Builder()
            .connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
            .readTimeout(8, java.util.concurrent.TimeUnit.SECONDS)
            .writeTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .connectionPool(okhttp3.ConnectionPool(5, 5, java.util.concurrent.TimeUnit.MINUTES))
            .build()
        val request = Request.Builder()
            .url(url)
            .build()

        client.newCall(request).execute().use { response ->
            Log.d("CommentDetailScreen", "获取回复列表响应 - 状态码: ${response.code}")
            if (!response.isSuccessful) {
                Log.e("CommentDetailScreen", "获取回复列表失败 - 状态码: ${response.code}")
                throw IOException("Unexpected code $response")
            }

            val responseBody = response.body?.string()
            Log.d("CommentDetailScreen", "获取回复列表响应体: $responseBody")
            val gson = Gson()
            val apiResp: CommentApiResponse<NestedData> = gson.fromJson(
                responseBody,
                object : TypeToken<CommentApiResponse<NestedData>>() {}.type
            )
            Log.d("CommentDetailScreen", "解析后的API响应: success=${apiResp.success}, data=${apiResp.data}")
            if (apiResp.success) {
                Log.d("CommentDetailScreen", "回复列表原始数据: ${apiResp.data.replies}")
                // 将Map转换为Comment对象
                val comments = apiResp.data.replies.map { commentMap ->
                    Comment(
                        id = (commentMap["id"] as? Number)?.toLong() ?: 0L,
                        postId = (commentMap["postId"] as? Number)?.toLong() ?: 0L,
                        userId = (commentMap["userId"] as? Number)?.toLong() ?: 0L,
                        content = commentMap["content"] as? String ?: "",
                        likeCount = (commentMap["likeCount"] as? Number)?.toInt() ?: 0,
                        isLiked = commentMap["isLiked"] as? Boolean ?: false,
                        createdAt = commentMap["createdAt"] as? String ?: "",
                        author = commentMap["author"] as? String ?: "匿名用户",
                        authorAvatar = commentMap["authorAvatar"] as? String, // 🔥 添加作者头像字段
                        parentId = (commentMap["parentId"] as? Number)?.toLong(),
                        rootId = (commentMap["rootId"] as? Number)?.toLong(),
                        isDeleted = commentMap["isDeleted"] as? Boolean ?: false
                    )
                }
                Log.d("CommentDetailScreen", "转换后的回复列表: ${comments.size} 条")
                comments
            } else {
                Log.e("CommentDetailScreen", "API返回失败: ${apiResp}")
                emptyList()
            }
        }
    }
}

// 发送回复的函数
suspend fun addReply(postId: Long, parentId: Long, rootId: Long, content: String, userId: Long): com.sddnytsh.body_buildingsystem.screens.CommentAddResponse {
    data class PostCommentRequest(
        val postId: Long,
        val userId: Long,
        val parentId: Long?,
        val rootId: Long?,
        val content: String
    )

    return withContext(Dispatchers.IO) {
        val url = "${NetworkConfig.BASE_URL}/api/post-comments"

        // 创建请求体 - 直接发送PostCommentRequest对象
        val commentRequest = PostCommentRequest(postId, userId, parentId, rootId, content)
        val gson = Gson()
        val requestBody = gson.toJson(commentRequest).toRequestBody("application/json".toMediaType())
        
        // 添加调试日志
        Log.d("CommentDetailScreen", "发送回复请求 - postId: $postId, userId: $userId, parentId: $parentId, rootId: $rootId, content: $content")
        Log.d("CommentDetailScreen", "请求体: ${gson.toJson(commentRequest)}")

        val client = OkHttpClient.Builder()
            .connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
            .readTimeout(8, java.util.concurrent.TimeUnit.SECONDS)
            .writeTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .connectionPool(okhttp3.ConnectionPool(5, 5, java.util.concurrent.TimeUnit.MINUTES))
            .build()
        val request = Request.Builder()
            .url(url)
            .post(requestBody)
            .addHeader("Content-Type", "application/json")
            .build()

        try {
            client.newCall(request).execute().use { response ->
                val responseBody = response.body?.string() ?: ""
                Log.d("CommentDetailScreen", "发送回复响应 - 状态码: ${response.code}, 响应体: $responseBody")
                
                if (!response.isSuccessful) {
                    Log.e("CommentDetailScreen", "发送回复失败 - 状态码: ${response.code}, 响应体: $responseBody")
                    throw IOException("Unexpected code $response")
                }

                val result = gson.fromJson(responseBody, com.sddnytsh.body_buildingsystem.screens.CommentAddResponse::class.java)
                Log.d("CommentDetailScreen", "发送回复成功 - result: $result")
                result
            }
        } catch (e: Exception) {
            Log.e("CommentDetailScreen", "发送回复异常: ${e.message}", e)
            throw e
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CommentDetailScreen(navController: NavController, commentId: Long) {
    val context = androidx.compose.ui.platform.LocalContext.current
    Log.d("CommentDetailScreen", "=== 评论详情页面已加载 - commentId: $commentId ===")
    
    // 状态管理
    var comment by remember { mutableStateOf<Comment?>(null) }
    var replies by remember { mutableStateOf<List<Comment>>(emptyList()) }
    var isLoading by remember { mutableStateOf(true) }
    var errorMessage by remember { mutableStateOf<String?>(null) }
    
    // 回复输入相关状态
    var showReplyInput by remember { mutableStateOf(false) }
    var newReply by remember { mutableStateOf("") }
    var isSubmittingReply by remember { mutableStateOf(false) }
    
    val coroutineScope = rememberCoroutineScope()
    val communityApiService = remember { CommunityApiService() }

    // 从API获取评论详情和回复列表
    LaunchedEffect(commentId) {
        Log.d("CommentDetailScreen", "=== LaunchedEffect 开始执行 - commentId: $commentId ===")
        
        // 防止重复加载
        if (comment != null && replies.isNotEmpty()) {
            Log.d("CommentDetailScreen", "数据已存在，跳过重复加载 - commentId: $commentId")
            return@LaunchedEffect
        }
        
        isLoading = true
        errorMessage = null

        try {
            val currentUserId = UserState.currentUserId
            Log.d("CommentDetailScreen", "开始加载评论详情 - commentId: $commentId, currentUserId: $currentUserId")
            // 获取评论详情
            val commentResult = getCommentById(commentId, currentUserId)
            if (commentResult != null) {
                Log.d("CommentDetailScreen", "获取评论详情成功 - comment.id: ${commentResult.id}, comment.postId: ${commentResult.postId}")
                comment = commentResult
                
                // 初始化回复输入框为 @昵称 格式
                newReply = "@${commentResult.author ?: "用户${commentResult.userId}"} "
                Log.d("CommentDetailScreen", "初始化回复输入框: $newReply")
                
                // 获取回复列表
                val repliesResult = getRepliesByCommentId(commentId, currentUserId)
                Log.d("CommentDetailScreen", "获取回复列表成功 - 回复数量: ${repliesResult.size}")
                replies = repliesResult
            } else {
                Log.e("CommentDetailScreen", "获取评论详情失败 - commentId: $commentId")
                errorMessage = "评论不存在或已被删除"
            }
        } catch (e: Exception) {
            errorMessage = "加载失败: ${e.message}"
        } finally {
            isLoading = false
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("评论详情") },
                navigationIcon = {
                    IconButton(onClick = { navController.popBackStack() }) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "返回")
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color(0xFF4361EE),
                    titleContentColor = Color.White,
                    navigationIconContentColor = Color.White
                )
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .background(Color(0xFFF5F5F5))
        ) {
            // 加载状态
            if (isLoading) {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator()
                }
            }
            // 错误状态
            else if (errorMessage != null) {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    Column(horizontalAlignment = Alignment.CenterHorizontally) {
                        Text(
                            text = errorMessage ?: "未知错误",
                            color = MaterialTheme.colorScheme.error
                        )
                        Spacer(modifier = Modifier.height(16.dp))
                        Button(onClick = {
                            // 重新加载数据
                            isLoading = true
                            errorMessage = null
                        }) {
                            Text("重试")
                        }
                    }
                }
            }
            // 正常显示内容
            else if (comment != null) {
                // 一级评论内容区域（固定）
                CommentDetailContent(
                    comment = comment!!,
                    replies = replies,
                    showReplyInput = showReplyInput,
                    onReplyClick = { 
                        showReplyInput = !showReplyInput
                    }
                )

                // 回复输入框（固定在评论下方）
                if (showReplyInput) {
                    ReplyInputSection(
                        replyText = newReply,
                        onReplyChange = { newReply = it },
                        isSubmitting = isSubmittingReply,
                        onSendReply = {
                            Log.d("CommentDetailScreen", "=== 点击发送回复按钮 ===")
                            coroutineScope.launch {
                                val currentUserId = UserState.currentUserId
                                Log.d("CommentDetailScreen", "当前用户ID: $currentUserId, 回复内容: $newReply")
                                if (currentUserId != null && newReply.isNotBlank()) {
                                    isSubmittingReply = true
                                    try {
                                        Log.d("CommentDetailScreen", "准备发送回复 - comment.id: ${comment!!.id}, comment.postId: ${comment!!.postId}, comment.rootId: ${comment!!.rootId}")
                                        val result = addReply(
                                            postId = comment!!.postId,
                                            parentId = comment!!.id,
                                            rootId = comment!!.rootId ?: comment!!.id,
                                            content = newReply.trim(),
                                            userId = currentUserId
                                        )
                                        if (result.success) {
                                            Log.d("CommentDetailScreen", "回复发送成功，开始重新加载回复列表")
                                            // 重新初始化输入框为 @昵称 格式
                                            newReply = "@${comment!!.author ?: "用户${comment!!.userId}"} "
                                            Log.d("CommentDetailScreen", "重新初始化回复输入框: $newReply")
                                            // 重新加载回复
                                            val repliesResult = getRepliesByCommentId(comment!!.id, currentUserId)
                                            Log.d("CommentDetailScreen", "重新加载回复列表完成 - 回复数量: ${repliesResult.size}")
                                            replies = repliesResult
                                        }
                                    } catch (e: Exception) {
                                        // 发送回复失败，保持静默
                                    } finally {
                                        isSubmittingReply = false
                                    }
                                }
                            }
                        }
                    )
                }

                // 回复标题
                Text(
                    text = "回复 (${replies.size})",
                    modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),
                    style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.SemiBold),
                    color = Color(0xFF333333)
                )

                // 回复列表（可滚动）
                Box(
                    modifier = Modifier.weight(1f)
                ) {
                    if (replies.isEmpty()) {
                        Box(
                            modifier = Modifier.fillMaxSize(),
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                text = "暂无回复，快来发表第一条回复吧~",
                                color = Color.Gray,
                                style = MaterialTheme.typography.bodyMedium
                            )
                        }
                    } else {
                        LazyColumn(
                            modifier = Modifier.fillMaxSize(),
                            contentPadding = PaddingValues(horizontal = 16.dp),
                            verticalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            Log.d("CommentDetailScreen", "渲染回复列表 - 回复数量: ${replies.size}")
                            replies.forEach { reply ->
                                Log.d("CommentDetailScreen", "回复内容: ${reply.content}, parentId: ${reply.parentId}, rootId: ${reply.rootId}")
                            }
                            
                            // 显示主评论
                            item {
                                CommentItem(
                                    comment = comment!!,
                                    onReplyClick = { /* 主评论不需要回复功能 */ }
                                )
                            }
                            
                            // 显示分隔线
                            item {
                                Divider(
                                    modifier = Modifier.padding(vertical = 8.dp),
                                    color = Color.Gray.copy(alpha = 0.3f)
                                )
                            }
                            
                            // 显示回复列表
                            items(replies) { reply ->
                                NestedCommentItem(
                                    comment = reply,
                                    parentComment = comment!!
                                )
                            }
                            
                            // 底部空白
                            item {
                                Spacer(modifier = Modifier.height(80.dp))
                            }
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun CommentDetailContent(
    comment: Comment,
    replies: List<Comment>,
    showReplyInput: Boolean,
    onReplyClick: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            // 用户信息
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.fillMaxWidth()
            ) {
                // 头像
                if (comment.authorAvatar != null) {
                    SimpleAvatarImage(
                        avatarUrl = comment.authorAvatar,
                        fallbackName = comment.author ?: "用户",
                        size = 40.dp
                    )
                } else {
                    DefaultAvatar(
                        name = comment.author ?: "用户",
                        size = 40.dp
                    )
                }
                
                Spacer(modifier = Modifier.width(12.dp))
                
                // 用户名和时间
                Column(modifier = Modifier.weight(1f)) {
                    Text(
                        text = comment.author ?: "匿名用户",
                        style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.SemiBold),
                        color = Color(0xFF333333)
                    )
                    Text(
                        text = DateUtils.formatDate(comment.createdAt),
                        style = MaterialTheme.typography.bodySmall,
                        color = Color.Gray
                    )
                }
            }
            
            Spacer(modifier = Modifier.height(12.dp))
            
            // 评论内容
            Text(
                text = comment.content,
                style = MaterialTheme.typography.bodyMedium,
                color = Color(0xFF555555),
                lineHeight = 20.sp,
                modifier = Modifier.fillMaxWidth()
            )
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 互动按钮
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                // 点赞按钮
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.clickable { 
                        // 点赞功能
                    }
                ) {
                    Icon(
                        imageVector = if (comment.isLiked) Icons.Default.ThumbUp else Icons.Default.ThumbUpOffAlt,
                        contentDescription = "点赞",
                        tint = if (comment.isLiked) Color(0xFFE91E63) else Color.Gray,
                        modifier = Modifier.size(20.dp)
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text(
                        text = comment.likeCount.toString(),
                        style = MaterialTheme.typography.bodySmall,
                        color = if (comment.isLiked) Color(0xFFE91E63) else Color.Gray
                    )
                }
                
                // 回复按钮
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.clickable { onReplyClick() }
                ) {
                    Icon(
                        imageVector = Icons.Default.Comment,
                        contentDescription = "回复",
                        tint = if (showReplyInput) Color(0xFF4361EE) else Color.Gray,
                        modifier = Modifier.size(20.dp)
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text(
                        text = replies.size.toString(),
                        style = MaterialTheme.typography.bodySmall,
                        color = if (showReplyInput) Color(0xFF4361EE) else Color.Gray
                    )
                }
            }
        }
    }
}

@Composable
fun ReplyInputSection(
    replyText: String,
    onReplyChange: (String) -> Unit,
    isSubmitting: Boolean,
    onSendReply: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 8.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Row(
            modifier = Modifier.padding(12.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            OutlinedTextField(
                value = replyText,
                onValueChange = onReplyChange,
                modifier = Modifier.weight(1f),
                placeholder = { Text("输入回复内容...") },
                singleLine = true,
                enabled = !isSubmitting,
                colors = TextFieldDefaults.colors(
                    focusedContainerColor = Color.Transparent,
                    unfocusedContainerColor = Color.Transparent
                )
            )
            
            Spacer(modifier = Modifier.width(8.dp))
            
            IconButton(
                onClick = onSendReply,
                enabled = replyText.isNotBlank() && !isSubmitting
            ) {
                if (isSubmitting) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(20.dp),
                        strokeWidth = 2.dp
                    )
                } else {
                    Icon(
                        imageVector = Icons.Filled.Send,
                        contentDescription = "发送回复",
                        tint = if (replyText.isNotBlank()) Color(0xFF4361EE) else Color.Gray
                    )
                }
            }
        }
    }
}

@Composable
fun NestedCommentItem(
    comment: Comment,
    parentComment: Comment
) {
    var isLiked by remember { mutableStateOf(comment.isLiked) }
    var likeCount by remember { mutableStateOf(comment.likeCount) }
    val coroutineScope = rememberCoroutineScope()
    val communityApiService = remember { CommunityApiService() }

    Card(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(8.dp),
    ) {
        Row(
            modifier = Modifier.padding(12.dp),
            verticalAlignment = Alignment.Top
        ) {
            // 用户头像
            if (comment.authorAvatar != null) {
                SimpleAvatarImage(
                    avatarUrl = comment.authorAvatar,
                    fallbackName = comment.author ?: "用户",
                    size = 32.dp
                )
            } else {
                DefaultAvatar(
                    name = comment.author ?: "用户",
                    size = 32.dp
                )
            }

            Spacer(modifier = Modifier.width(12.dp))

            // 回复内容
            Column(
                modifier = Modifier.weight(1f)
            ) {
                // 用户名和时间
                Row(
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = comment.author ?: "用户${comment.userId}",
                        style = MaterialTheme.typography.bodyMedium.copy(
                            fontWeight = FontWeight.Medium,
                            color = Color(0xFF333333)
                        )
                    )
                    
                    Spacer(modifier = Modifier.width(8.dp))
                    
                    Text(
                        text = DateUtils.formatDate(comment.createdAt),
                        style = MaterialTheme.typography.bodySmall.copy(
                            color = Color(0xFF999999)
                        )
                    )
                }

                Spacer(modifier = Modifier.height(4.dp))

                // 回复内容
                Text(
                    text = comment.content,
                    style = MaterialTheme.typography.bodyMedium.copy(
                        color = Color(0xFF333333)
                    ),
                    modifier = Modifier.fillMaxWidth()
                )

                Spacer(modifier = Modifier.height(8.dp))

                // 点赞按钮（二级评论只能点赞，不能回复）
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.clickable {
                        val currentUserId = UserState.currentUserId
                        if (currentUserId != null) {
                            coroutineScope.launch {
                                try {
                                    val result = communityApiService.toggleCommentLike(currentUserId, comment.id)
                                    if (result.isSuccess) {
                                        isLiked = !isLiked
                                        likeCount = if (isLiked) likeCount + 1 else likeCount - 1
                                    }
                                } catch (e: Exception) {
                                    // 处理错误
                                }
                            }
                        }
                    }
                ) {
                    Icon(
                        imageVector = if (isLiked) Icons.Filled.ThumbUp else Icons.Default.ThumbUpOffAlt,
                        contentDescription = "点赞",
                        tint = if (isLiked) Color(0xFFE91E63) else Color(0xFF999999),
                        modifier = Modifier.size(16.dp)
                    )
                    
                    Spacer(modifier = Modifier.width(4.dp))
                    
                    Text(
                        text = likeCount.toString(),
                        style = MaterialTheme.typography.bodySmall.copy(
                            color = if (isLiked) Color(0xFFE91E63) else Color(0xFF999999)
                        )
                    )
                }
            }
        }
    }
}